﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace Common.Tools
{
    public class HttpHelper
    {
        public static readonly string _chromeUserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36";

        public static readonly string _ieUserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; rv:11.0) like Gecko";


        public static string Get(string url)
        {
            return Get(url, 4000, null, null, null, null);
        }

        public static string Get(string url, int timeout, CookieCollection cookies)
        {
            return Get(url, timeout, null, null, cookies, null);
        }

        public static string Post(string url, string parameters)
        {
            return Post(url, parameters, 4000, null, null, null, null);
        }

        public static string Post(string url, string parameters, int timeout, CookieCollection cookies)
        {
            return Post(url, parameters, timeout, null, null, cookies, null);
        }

        #region 核心方法
        /// <summary>
        /// 获得GET方式的HTTP请求后响应的数据
        /// </summary>
        /// <param name="url">请求的URL</param>
        /// <param name="timeout">请求的超时时间(以毫秒为单位)</param>
        /// <param name="contentType">设置为"application/x-www-form-urlencoded"或者是"application/json"</param>
        /// <param name="userAgent">请求的客户端浏览器信息，可以为空</param>
        /// <param name="cookies">随同HTTP请求发送的Cookie信息，如果不需要身份验证可以为空</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>服务器返回字符串</returns>
        public static string Get(string url, int timeout, string contentType, string userAgent, CookieCollection cookies, Encoding encoding)
        {
            var responseString = string.Empty;
            try
            {
                if (encoding == null) encoding = Encoding.UTF8;

                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = "GET";
                if (timeout > 4000)
                {
                    request.Timeout = timeout;
                }
                else
                {
                    request.Timeout = 8000;
                }
                if (string.IsNullOrWhiteSpace(contentType))
                {
                    request.ContentType = "application/x-www-form-urlencoded";
                }
                else
                {
                    request.ContentType = contentType;
                }
                if (string.IsNullOrWhiteSpace(userAgent))
                {
                    request.UserAgent = _ieUserAgent;
                }
                else
                {
                    request.UserAgent = userAgent;
                }
                if (cookies != null)
                {
                    request.CookieContainer = new CookieContainer();
                    request.CookieContainer.Add(cookies);
                }

                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (StreamReader sr = new StreamReader(responseStream, encoding))
                        {
                            responseString = sr.ReadToEnd();
                        }
                    }
                }
                request.Abort();
                request = null;
            }
            catch (WebException ex)
            {
                responseString = ex.Message;
            }
            return responseString;
        }

        /// <summary>
        /// 获得POST方式的HTTP请求后响应的数据
        /// </summary>
        /// <param name="url">请求的URL</param>
        /// <param name="parameters">随同请求POST的参数名称及参数值字典</param>
        /// <param name="timeout">请求的超时时间(以毫秒为单位)</param>
        /// <param name="contentType">设置为"application/x-www-form-urlencoded"或者是"application/json"</param>
        /// <param name="userAgent">请求的客户端浏览器信息，可以为空</param>
        /// <param name="cookies">随同HTTP请求发送的Cookie信息，如果不需要身份验证可以为空</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>服务器返回字符串</returns>
        public static string Post(string url, string parameters, int timeout, string contentType, string userAgent, CookieCollection cookies, Encoding encoding)
        {
            var responseString = string.Empty;
            try
            {
                if (encoding == null) encoding = Encoding.UTF8;

                HttpWebRequest request = null;
                //如果是发送HTTPS请求  
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    request = WebRequest.Create(url) as HttpWebRequest;
                    request.ProtocolVersion = HttpVersion.Version10;
                }
                else
                {
                    request = WebRequest.Create(url) as HttpWebRequest;
                }
                request.Method = "POST";
                if (timeout > 4000)
                {
                    request.Timeout = timeout;
                }
                else
                {
                    request.Timeout = 8000;
                }
                if (string.IsNullOrWhiteSpace(contentType))
                {
                    request.ContentType = "application/x-www-form-urlencoded";
                }
                else
                {
                    request.ContentType = contentType;
                }
                if (string.IsNullOrWhiteSpace(userAgent))
                {
                    request.UserAgent = _ieUserAgent;
                }
                else
                {
                    request.UserAgent = userAgent;
                }
                if (cookies != null)
                {
                    request.CookieContainer = new CookieContainer();
                    request.CookieContainer.Add(cookies);
                }

                if (!string.IsNullOrWhiteSpace(parameters))
                {
                    //方式一
                    byte[] postBytes = encoding.GetBytes(parameters);
                    //request.ContentLength = postBytes.Length;
                    using (Stream requestStream = request.GetRequestStream())
                    {
                        requestStream.Write(postBytes, 0, postBytes.Length);
                    }

                    //方式二
                    ////不需要指定长度,否则报错(在写入所有字节之前不能关闭流。)
                    ////request.ContentLength = myEncode.GetByteCount(param);
                    //using (Stream requestStream = request.GetRequestStream())
                    //{
                    //    using (StreamWriter sw = new StreamWriter(requestStream, encoding))
                    //    {
                    //        sw.Write(parameters);
                    //    }
                    //}
                }


                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (StreamReader sr = new StreamReader(responseStream, encoding))
                        {
                            responseString = sr.ReadToEnd();
                        }
                    }
                }
                request.Abort();
                request = null;
            }
            catch (Exception ex)
            {
                responseString = ex.Message;
            }
            return responseString;
        }

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受  
        }
        #endregion

        /// <summary>
        /// 远程获取图片流
        /// </summary>
        /// <param name="url"></param>
        /// <param name="timeout"></param>
        /// <param name="userAgent"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static Stream GetResponseStream(string url, int timeout, string userAgent, Encoding encoding)
        {
            try
            {
                if (encoding == null) encoding = Encoding.UTF8;

                HttpWebRequest request = null;
                //如果是发送HTTPS请求  
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    request = WebRequest.Create(url) as HttpWebRequest;
                    request.ProtocolVersion = HttpVersion.Version10;
                }
                else
                {
                    request = WebRequest.Create(url) as HttpWebRequest;
                }
                request.Method = "GET";
                if (timeout > 4000)
                {
                    request.Timeout = timeout;
                }
                else
                {
                    request.Timeout = 8000;
                }
                if (string.IsNullOrWhiteSpace(userAgent))
                {
                    request.UserAgent = _ieUserAgent;
                }
                else
                {
                    request.UserAgent = userAgent;
                }
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                return response.GetResponseStream();
            }
            catch (Exception ex)
            {
                return null;
            }
        }

    }
}
